#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <signal.h> 
#include <stdlib.h>       
#include <string.h>
#include <pthread.h>
//#include <sys/sem.h>
#include <errno.h>
#include <sys/ipc.h>
//#include <sys/msg.h>
#include <sys/timeb.h>
#include <sys/socket.h>
//#include <sys/socketvar.h>
#include <sys/select.h>
#include <sys/stat.h>
#include <arpa/inet.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <semaphore.h>
#include <string.h>
#include <termios.h>
#include <linux/input.h>
#include <semaphore.h>
#include <linux/shm.h>
#include <asm/unistd.h>
#include <sys/poll.h>

#include "common.h"

void commandServer(struct recvData *recvData)
{
		if(recvData == NULL)
		{
				printf("recvData == NULL ! {%s(%d)}\n",__FILE__,__LINE__);
				return;	
		}
		
		struct packageFilter filter;
		int ret = explainPackageHead(recvData, &filter);
		if(ret < 0)
		{
				return;	
		}
		
		if(filter.protoSlaveType != 0x00)
		{
				printf("filter.protoSlaveType != 0x00 ! filter.protoSlaveType = %d {%s,%d}\n", filter.protoSlaveType, __FILE__,__LINE__);
				return;
		}
		
		//exec
		unsigned char *revData = recvData->buf;
		struct packageFilter *pFilter = &filter;
		
		char *command = (char*)(pFilter->pData);
		if(command == NULL)
		{
				printf("command == NULL ! {%s(%d)}\n",__FILE__,__LINE__);
				return;
		}
		
		unsigned char privateData[4];
		memcpy(privateData, revData + recvData->count - 4, 4); 
		
		revData[recvData->count - 4] = '\0';
		printf("command = %s\n", command);
		system(command);		
		
		
		//return back package
		unsigned char dataDirection = 0x01;
		unsigned short dataLen = 5;
	
		createProtoCombinationData(revData + 3, pFilter->deviceType, dataDirection, pFilter->communicationWay, dataLen);
		
		unsigned char checkCode = 0;
		unsigned int headLen = recvData->count - pFilter->dataLen;
		unsigned int packageSize = headLen + 5;
		for(unsigned char i=0; i<headLen-1; i++)
		{
				checkCode += revData[i];
		}
		revData[headLen - 1] = checkCode;
		
		revData[headLen] = 0; //0:success 1:fail
		memcpy(recvData + 1, privateData, 4);

		MainSend(recvData->buf, packageSize, &(recvData->addr));
}

